import api from './../api'
import CONFIG from './../config'
const state = {
  //个人中心信息
  personalInfo:{
    name:'',
    email:'',
    phone:'',
    loan_record:0,
    overdue_record:0,
    wait_pay:0
  },
  //用户信息
  userInfo:{},
  // isVerified:0, //0  未实名 1已实名
  // userType:1,  //1为个人用户 2企业用户
  isHasInfoId:false,
  qiniuToken:'',
  title:'',
  products:{
    data:[],
    current_page:1,
    total:1,
    per_page:10,
    last_page:1
  },
};

const mutations = {
  setProducts(state,obj){
    state.products = obj;
  },
  changeTitle(state,value){
    state.title = value;
  },
  initUser(state){
    state.personalInfo = {};
    state.userInfo = {};
    state.qiniuToken = '';
    state.isHasInfoId = false;
  },
  setPersonalInfo(state,obj){
    state.personalInfo = obj;
  },
  setUserInfo(state,obj){
    state.userInfo = obj;
  },
  setIsHasInfoId(state,value){
    state.isHasInfoId = value;
  },
  setQiniuToken(state,value){
    state.qiniuToken = value;
  }
};

const actions = {
  changeTitleAction(ctx,value){
    ctx.commit('changeTitle',value)
  },
  initUserAction(ctx){
    ctx.commit('initUser')
  },
  getPersonalInfoAction(ctx,params){
    api.getPersonal().then((res)=>{
      ctx.commit('setPersonalInfo',res.data)
    }).catch(()=>{
    })
  },
  getUserInfoAction(ctx,params){
    return new Promise((success,error) =>{
      let apiName = CONFIG.userType == 2 ? 'getEnterpriseInfo' : 'getUserInfo';
        api[apiName]().then((res)=>{
          ctx.commit('setUserInfo',res.data);
          if(res.data.info_id){
            ctx.commit('setIsHasInfoId',true)
          }
          success(res.data)
        }).catch((err)=>{
          error(err)
        })
    })
  },
  setQiniuTokenAction(ctx,params) {
    return new Promise((success,error)=>{
      api.uploadToken().then((res)=>{
        ctx.commit('setQiniuToken',res.data);
          success(res)
      }).catch((err)=>{
        error(err)
      })
    })
  },
  getProductsAction(ctx,params){
    return new Promise((success,error)=>{
      if(ctx.state.products.data.length===0){
        api.getProducts().then((res)=>{
        ctx.commit('setProducts',res);
        success(res)
      }).catch((err)=>{
        error(err)
      })
      }else {
        success(ctx.state.products)
      }
    })
  }
};

export default {
  state,
  mutations,
  actions
}
